package cn.itcast.controller.log;

import cn.itcast.domain.system.SysLog;
import cn.itcast.domain.system.User;
import cn.itcast.service.system.SysLogService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.UUID;

@Component
@Aspect
public class AspectLog {


    @Autowired
    private HttpServletRequest request;

    @Autowired
    private HttpSession session;

    @Autowired
    private SysLogService sysLogService;

    @Around("execution(* cn.itcast.controller.*.*.*(..))")
    public Object saveLog(ProceedingJoinPoint pjp) throws Throwable{
        SysLog sysLog = new SysLog();

        sysLog.setId(UUID.randomUUID().toString()); //设置主键
        sysLog.setTime(new Date());     //当前时间
        sysLog.setIp(request.getRemoteAddr()); //操作人的ip地址

        User user = (User) session.getAttribute("loginUser");
        if(user!=null){
            sysLog.setUserName(user.getUserName());
            sysLog.setCompanyName(user.getCompanyName());
            sysLog.setCompanyId(user.getCompanyId());
        }

        MethodSignature signature = (MethodSignature) pjp.getSignature(); //方法签名中包括了方法和这个方法上的注解内容

        Method method = signature.getMethod(); //获取到了当前方法对象
        sysLog.setMethod(method.getName());  //方法名

        if(method.isAnnotationPresent(RequestMapping.class)){  //判断这个方法上是否有RequestMapping注解
            RequestMapping annotation = method.getAnnotation(RequestMapping.class);//获取到这个方法的RequestMapping注解
            sysLog.setAction(annotation.name()); // 方法的说明 取的是@RequestMapping注解上的name属性的值
        }

        sysLogService.save(sysLog);

        return pjp.proceed();  //执行原方法
    }


}
